package com.csdig.cms.directive;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.csdig.cms.model.ext.ContentExt;
import com.csdig.cms.service.ContentService;
import com.csdig.cms.utils.DirectiveUtils;
import com.csdig.cms.utils.FrontUtils;

import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@Service("contentListDirective")
public class ContentListDirective implements TemplateDirectiveModel {

	/**
	 * 输入参数，文章ID。允许多个文章ID，用","分开。排斥其他所有筛选参数。
	 */
	public static final String CHANNEL_ID = "channel_id";

	public static final String ORDER_BY = "orderBy";

//	public static final String HAS_ChILD = "hasChild";

	@SuppressWarnings("unchecked")
	@Override
	public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		Integer channelId = DirectiveUtils.getInt(CHANNEL_ID, params);
		String orderBy = DirectiveUtils.getString(ORDER_BY, params);
//		Boolean hasChild = DirectiveUtils.getBool(HAS_ChILD, params);
//		hasChild = ((hasChild == null) ? Boolean.FALSE : hasChild);
		int first = FrontUtils.getFirst(params);
		int count = FrontUtils.getCount(params);
		List<ContentExt> list = new ArrayList<ContentExt>();

		try {
			list = contentService.getListByIdsForTag(channelId, first, count, orderBy);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
		paramWrap.put(DirectiveUtils.OUT_LIST, ObjectWrapper.DEFAULT_WRAPPER.wrap(list));
		Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);
		body.render(env.getOut());
		DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
	}

	@Autowired
	private ContentService contentService;

}
